﻿using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shell;
using DimensionsHelper.Client.Navigation;
using DimensionsHelper.Client.ViewModels;
using DimensionsHelper.Client.Converters;
using NavigationService = DimensionsHelper.Client.Navigation.NavigationService;

namespace DimensionsHelper.Client.Views;

public partial class MainWindow
{
    private readonly NavigationService _navigationService;
    private double _cachedStatusBarHeight;
    private double _cachedTaskPanelHeight;
    private bool _isTaskPanelOpen;

    public MainWindow(IServiceProvider serviceProvider)
    {
        _navigationService = serviceProvider.GetRequiredService<NavigationService>();
        DataContext = serviceProvider.GetRequiredService<MainWindowViewModel>();

        FontSizePtConverter.SetDpiFromVisual(this);
        InitializeComponent();

        _navigationService.SetFrame(RootContentFrame);
        _navigationService.Navigating += OnNavigating;

        WindowChrome.SetWindowChrome(
            this,
            new WindowChrome
            {
                CaptionHeight = 50,
                CornerRadius = default,
                GlassFrameThickness = new Thickness(-1),
                ResizeBorderThickness = ResizeMode == ResizeMode.NoResize
                    ? default
                    : new Thickness(4),
                UseAeroCaptionButtons = false
            });

        StateChanged += MainWindow_StateChanged;
    }
    

    private void MainWindow_StateChanged(object? sender, EventArgs e)
    {
        MainGrid.Margin = WindowState == WindowState.Maximized ? new Thickness(8) : default;
        MaximizeIcon.Text = WindowState == WindowState.Maximized ? "\uE923" : "\uE922";
    }


    private void MinimizeWindow(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState.Minimized;
    }


    private void MaximizeWindow(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
    }

    private void CloseWindow(object sender, RoutedEventArgs e)
    {
        Application.Current.Shutdown();
    }


    private void ToggleTaskPanelVisibility(object sender, RoutedEventArgs e)
    {
        if (!_isTaskPanelOpen && _cachedStatusBarHeight == 0)
        {
            _cachedStatusBarHeight = StatusBarRow.ActualHeight;
        }

        if (_isTaskPanelOpen && _cachedTaskPanelHeight == 0)
        {
            _cachedTaskPanelHeight = StatusBarRow.ActualHeight;
        }

        _isTaskPanelOpen = !_isTaskPanelOpen;
        ToggleTaskPanelVisibilityButtonIcon.Text = _isTaskPanelOpen ? "\xE70D" : "\xE7C4";
        StatusBar.Visibility = _isTaskPanelOpen ? Visibility.Collapsed : Visibility.Visible;
        TaskPanelGrid.Visibility = _isTaskPanelOpen ? Visibility.Visible : Visibility.Collapsed;
        GridSplitter.Visibility = TaskPanelGrid.Visibility;

        if (!_isTaskPanelOpen && _cachedStatusBarHeight > 0)
        {
            StatusBarRow.Height = new GridLength(_cachedStatusBarHeight);
        }
        else if (_isTaskPanelOpen && _cachedTaskPanelHeight > 0)
        {
            StatusBarRow.Height = new GridLength(_cachedTaskPanelHeight);
        }

        AutomationPeer peer = UIElementAutomationPeer.CreatePeerForElement((Button)sender);
        peer.RaiseNotificationEvent(
            AutomationNotificationKind.Other,
            AutomationNotificationProcessing.ImportantMostRecent,
            $"Task panel is {(_isTaskPanelOpen ? "shown" : "hidden")}",
            "ButtonClickedActivity");
    }


    private TreeViewItem? OnNavigationTreeSelectedItemChanged()
    {
        if (NavigationTree.SelectedItem is not NavigationTargetData targetData)
        {
            return null;
        }

        _navigationService.Navigate(targetData.PageType, targetData.ModelType, targetData.Key);
        if (NavigationTree.ItemContainerGenerator.ContainerFromItem(targetData) is TreeViewItem item)
        {
            item.BringIntoView();
            return item;
        }

        return null;
    }


    private void OnNavigating(object? sender, NavigatingEventArgs e)
    {
    }


    private void GridSplitter_DragCompleted(object sender, DragCompletedEventArgs e)
    {
        _cachedTaskPanelHeight = StatusBarRow.ActualHeight;
    }


    private void RootContentFrame_Navigated(object sender, NavigationEventArgs e)
    {
        ((MainWindowViewModel)DataContext).UpdateCanNavigateBack();
    }


    private void TreeView_Loaded(object sender, RoutedEventArgs e)
    {
        if (NavigationTree.Items.Count > 0)
        {
            TreeViewItem? firstItem = (TreeViewItem)NavigationTree.ItemContainerGenerator
                .ContainerFromItem(NavigationTree.Items[0]);
            if (firstItem != null)
            {
                firstItem.IsSelected = true;
            }
        }
    }

    private void NavigationTree_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (e.OriginalSource is ToggleButton)
        {
            return;
        }

        TreeViewItem? treeViewItem = OnNavigationTreeSelectedItemChanged();
        if (treeViewItem != null)
        {
            treeViewItem.IsExpanded = !treeViewItem.IsExpanded;
        }
    }
}